package com.ganzalang.gmall.promotion.service.impl;

import com.ganzalang.gmall.promotion.dto.*;
import com.ganzalang.gmall.promotion.service.CartRuleService;
import com.ganzalang.gmall.promotion.service.CouponService;
import com.ganzalang.gmall.promotion.service.PromotionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author Ganzalang
 * @description 购物车门面实现类
 * @Date 2022/4/3 22:56
 */
@Service
@RequiredArgsConstructor
public class CartRuleServiceImpl implements CartRuleService {

    /**
     * 促销活动服务
     */
    private final PromotionService promotionService;
    /**
     * 优惠券服务
     */
    private final CouponService couponService;

    /**
     * 处理购物
     *
     * @param context 购物车上下文
     * @return
     */
    @Override
    public CartRuleResult handle(CartRuleContext context) {
        CartRuleResult result = new CartRuleResult();
        for (CartPromotionItem cartPromotionItem : context.getCartItemList()) {
            // 每个促销活动都调用一次promotion接口
            PromotionContext promotionContext = new PromotionContext();
            promotionContext.setCartPromotionItem(cartPromotionItem);
            PromotionResult promotionRes = promotionService.handle(promotionContext);
            // 累加促销活动的结果
            sumUpResult(result, promotionRes);
        }
        // 处理优惠券
        if (!StringUtils.isEmpty(context.getCouponCode())) {
            CouponResult couponRes = couponService.handle(context, result);
            // 累加优惠券的结果
            sumUpCouponResult(result, couponRes);
        }

        return result;
    }

    /**
     * 累加优惠券的结果
     * @param result 累加促销活动的结果
     * @param couponRes 优惠券的结果
     */
    private void sumUpCouponResult(CartRuleResult result, CouponResult couponRes) {
        result.setCouponAmount(couponRes.getCouponAmount());
        result.setPayAmount(result.getPayAmount().subtract(couponRes.getCouponAmount()));
    }

    /**
     * 累加促销活动的结果
     *
     * @param result       购物车返回出去的结果
     * @param promotionRes 促销活动的结果
     */
    private void sumUpResult(CartRuleResult result, PromotionResult promotionRes) {
        result.setDiscountAmount(result.getDiscountAmount().add(promotionRes.getDiscountAmount()));
        result.setAmount(result.getAmount().add(promotionRes.getAmount()));
        result.setPayAmount(result.getPayAmount().add(promotionRes.getPayAmount()));
    }
}
